
let express = require('express')

let app = express()

app.use(express.static('static'))

// *.在所有接口前设置 处理post请求参数的中间件
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// 定义返回给客户端的数据
let arr = [
    { email: '123@qq.com', name: '张三', phone: '13309239088', group: '编辑组', isadmin: '是', status: true, pass: 1234 },
    { email: '124@qq.com', name: '李四', phone: '13309239089', group: '编辑组', isadmin: '是', status: true, pass: 1233  },
    { email: '125@qq.com', name: '王五', phone: '13309239086', group: '编辑组', isadmin: '是', status: true, pass: 1236  },
    { email: '126@qq.com', name: '刘七', phone: '13309239085', group: '编辑组', isadmin: '是', status: true, pass: 1235  },
    { email: '127@qq.com', name: '黄二', phone: '13309239084', group: '编辑组', isadmin: '是', status: true, pass: 1238  },
]

// 4.设置接口 函数就是请求处理器
// 列表渲染
app.get('/user/list', (req, res) => {
    res.send({ code: 200, msg: '列表渲染成功', list: arr })
})

// 分页
app.get('/user/page', (req, res) => {
    // 获取get类型请求的参数：req.query(解构参数)
    let { page, count } = req.query
    let newarr = arr.slice((page - 1) * count, page * count)
    res.send({ code: 200, msg: '分页成功', list: newarr })
})

// 模糊搜索
app.get('/user/search', (req, res) => {
    // 接收参数
    let { searchkey } = req.query
    // 根据参数，从用户的name属性中过滤
    let newarr = arr.filter((item) => {
        // includes() 返回true/false
        return item.name.includes(searchkey)
    })
    res.send({ code: 200, msg: '查找成功', list: newarr })
})

// 登陆
app.post('/user/login', (req, res) => {
    // 想要接收post类型请求的参数 必须提前设置能解析post请求参数的中间件 express.json和 express.urlencoded
    let { phone, pass } = req.body
    //用来自客户端的数据 做判断, 判断是否在服务端的用户列表中
    var i = arr.findIndex((item) => {
        return item.phone == phone && item.pass == pass;
    })

    //如果i不是-1, 说明来自客户端的数据是合法的.
    i != -1 ? res.send({ code: 200, msg: '登陆成功!', userinfo: arr[i], token: '' }) : res.send({ code: 400, msg: '登陆失败!' })
})

// 5.设置监听
app.listen(8080)
